<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules" label-width="130px">
      <el-form-item :label="$t('RegTabs_alias')" prop="name">
<!--      <el-form-item label="别名" prop="name">-->
        <el-input v-model.trim="form.name" style="width: 70%" :placeholder="$t('RegTabs_Pleaseenterauniquealias')" @keyup.enter.native="Login('form')"></el-input>
      </el-form-item>
      <el-form-item :label="$t('RegTabs_Warehouseaddress')" prop="url" v-if="name !== 'diy'" >
        <el-select v-model="form.url" :placeholder="$t('RegTabs_Pleaseselectwarehouseaddress')"  style="width: 70%">
          <el-option :label="item.name" :value="item.loginUrl" v-for="item in loginUrl" :key="item.url"></el-option>
        </el-select>
        <span class="tishi">{{$t('RegTabs_Please')}}</span>
      </el-form-item>
      <el-form-item :label="$t('RegTabs_username')" prop="username">
        <el-input v-model.trim="form.username" style="width: 70%" :placeholder="$t('RegTabs_enteroneusername')" @keyup.enter.native="Login('form')"></el-input>
      </el-form-item>
      <el-form-item :label="$t('RegTabs_password')" prop="password">
        <el-input type="password" v-model="form.password" :placeholder="$t('RegTabs_Pleaseinputapassword')" style="width: 70%" @keyup.enter.native="Login('form')"></el-input>
      </el-form-item>
      <el-form-item :label="$t('RegTabs_Warehouseaddress')" prop="url" v-if="name === 'diy'">
        <el-input v-model.trim="form.url" :placeholder="$t('RegTabs_Pleaseenterthewarehouseaddress')" @keyup.enter.native="Login('form')"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" style="background: #067FB5; color: #fff;" @click="Login('form')">{{ $t('RegTabs_Addnow') }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import Vue from 'vue'
import { Form, FormItem, Button, Input, Select, Option } from 'element-ui'
import http from '@/utils/http'
import { Base64 } from 'js-base64' // 编码插件
Vue.use(Form)
Vue.use(FormItem)
Vue.use(Button)
Vue.use(Input)
Vue.use(Select)
Vue.use(Option)

export default {
  data () {
    return {
      // 请求回来的注册表数据
      hubdata: [],
      // 添加注册表表单绑定
      form: {
        name: '',
        username: '',
        password: '',
        url: 'https://index.docker.io/v1/'
      },
      // 常用镜像仓库
      loginUrl: [
        { name: 'DockerHub', loginUrl: 'https://index.docker.io/v1/' },
        { name: '阿里云仓库-北京', loginUrl: 'https://registry.cn-beijing.aliyuncs.com' },
        { name: '腾讯云仓库-默认地域', loginUrl: 'https://ccr.ccs.tencentyun.com' },
        { name: 'Amazon仓库', loginUrl: 'https://aws_account_id.dkr.ecr.us-east-1.amazonaws.com' },
        { name: 'Quay仓库', loginUrl: 'https://quay.io' }
      ]
    }
  },
  computed:{
    rules(){
      if(this.$t){
       return {
          url: [
            { required: true, message: this.$t('RegTabs_Pleaseselectwarehouseaddress'), trigger: 'blur' }
          ],
          username: [
            { required: true, message: this.$t('RegTabs_enteroneusername'), trigger: 'blur' }
          ],
          name: [
            { required: true, message: this.$t('RegTabs_Pleaseenterauniquealias'), trigger: 'blur' }
          ],
          password: [
            { required: false, message: this.$t('RegTabs_Pleaseinputapassword'), trigger: 'blur' }
          ]
        }
      }else{
        return {
          url: [
            { required: true, message: '请选择或输入仓库地址', trigger: 'blur' }
          ],
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' }
          ],
          name: [
            { required: true, message: '请输入别名', trigger: 'blur' }
          ],
          password: [
            { required: false, message: '请输入密码', trigger: 'blur' }
          ]
        }
      }
    }
  },
  // 父组件传过来的当前tag名
  props: ['name'],
  watch: {
    // 监听name变化，更改
    name: function () {
      if (this.name === 'Hub') {
        this.form.url = 'https://index.docker.io/v1/'
      } else {
        this.form.url = ''
      }
    }
  },
  mounted () {
    // 请求注册表数据
    http({
      url: '/hubfind',
      method: 'GET',
      timeout: 2000000
    }).then(res => {
      if (res.Code === 200) {
        this.hubdata = res.Data
      }
    }).catch((err) => {
      return err
    })
  },
  methods: {
    // 添加注册表判断是否能够登录成功
    Login (form) {
      // 表单验证
      this.$refs[form].validate((valid) => {
        if (valid) {
          // 判断别名是否重复
          let arr = this.hubdata.filter(item => {
            return item.name === this.form.name
          })
          if (arr.length > 0) {
            return this.$message({
              showClose: true,
              message: '别名重复！',
              type: 'error'
            })
          }
          // 开启转圈圈
          this.loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          // 请求数据的data参数
          const data = {
            username: this.form.username,
            password: this.form.password,
            serveraddress: this.form.url
          }
          const docker = `curl --unix-socket /var/run/docker.sock -s -H "Content-Type:application/json" -d '${JSON.stringify(data)}' -X POST "http:/v1.40/auth"`
          // 发请求验证
          http({
            url: '/docker',
            method: 'POST',
            timeout: 2000000,
            data: {
              docker
            }
          }).then(res => {
            if (res.Code === 200) {
              this.hubadd()
            } else {
              this.loading.close()
              this.$message({
                showClose: true,
                message: '用户名或密码错误，请重试！',
                type: 'error'
              })
            }
          }).catch((err) => {
            return err
          })
        } else {
          return false
        }
      })
    },
    // 添加到注册表数据库
    hubadd () {
      const adddata = {
        name: this.form.name,
        username: this.form.username,
        password: Base64.encode(this.form.password),
        url: this.form.url,
        authentication: true
      }
      http({
        url: '/hubadd',
        method: 'POST',
        timeout: 2000000,
        data: {
          ...adddata
        }
      }).then(res => {
        this.loading.close()
        if (res.Code === 200) {
          this.$message({
            showClose: true,
            message: '注册表添加成功！',
            type: 'success'
          })
          // 告诉父组件请求成功，让table组件重新加载数据
          this.$emit('success')
          // 清空表单
          this.form.name = this.form.username = this.form.password = this.form.url = ''
        } else {
          this.$message({
            showClose: true,
            message: '注册表添加失败，请稍候再试！',
            type: 'error'
          })
        }
      }).catch((err) => {
        return err
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.tishi{
  font-size: 12px;
  color: #ccc;
  padding-left: 10px;
}
</style>
